package com.zhongpengcheng.fortune.es.advice;

import com.alibaba.fastjson.JSONObject;
import com.zhongpengcheng.fortune.es.common.pojo.Result;
import com.zhongpengcheng.fortune.es.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局response处理，在将返回数据写入response前执行
 *
 * @author zhongpengcheng
 */
@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

    @SuppressWarnings("NullableProblems")
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 返回JSONObject时不需要拦截
        return !returnType.getParameterType().equals(JSONObject.class);
    }

    @SuppressWarnings({"deprecation", "NullableProblems"})
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            // 为空包装success Result返回
            return JSONObject.toJSON(ResultUtils.success());
        }
        if (body instanceof Result) {
            // 为Result时包装后返回
            return JSONObject.toJSON(body);
        }
        if (body instanceof String) {
            // 为String时将response的ContentType设置为application/json;charset=UTF-8后包装返回
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            return JSONObject.toJSON(ResultUtils.success(body));
        }
        // 其余包装后返回
        return JSONObject.toJSON(ResultUtils.success(body));
    }
}
